package cn.xxy.datasource;

import cn.xxy.beans.DataSourceConfig;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.util.Map;

public class HikariDataSourceAdapter extends DataSourceAdapter {
	private HikariDataSource ds;
	@Override
	protected DataSource adapter(DataSourceConfig config) {
		ds = new HikariDataSource();
		ds.setDriverClassName(config.getDriverClass());
		ds.setJdbcUrl(config.getJdbcUrl());
		ds.setUsername(config.getUsername());
		ds.setPassword(config.getPassword());

		initAdapter();
		injectProperty(ds, config);
		return ds;
	}
	
	@Override
	protected DataSource adapter(Map<String, String> config) {
		ds = new HikariDataSource();
		initAdapter();
		injectProperty(ds, config);
		return ds;
	}
	protected void initAdapter() {
		if (ds != null) return;

		//ds.setAutoCommit(true);
		//ds.setMinimumIdle(1);
		//ds.setMaximumPoolSize(10);
		ds.setConnectionTimeout(3000);
//		ds.setMaxLifetime(1);
//		ds.setKeepaliveTime(111);
//		ds.setConnectionTestQuery("SELECT 1");
//		ds.setIdleTimeout(1);
		ds.setAllowPoolSuspension(false);
	}
	/**
	 * finalize()方法是在垃圾收集器删除对象之前对这个对象调用的。
	 *
	 * @throws Throwable
	 */
	protected void finalize() throws Throwable {
		if (ds != null) {
			ds.close();
		}
		super.finalize();
	}
}
